package com.android.personal.kotlin.activity

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.View
import android.widget.TextView
import com.android.personal.kotlin.R

/**
 * Created by zhangwentao on 2016/12/7.
 */
open class BaseAppCompatActivity : AppCompatActivity() {
    val TAG : String? = BaseAppCompatActivity::class.java.name
    private var mToolbarTitle: TextView? = null
    private var mToolbarSubTitle: TextView? = null
    private var mToolbar: Toolbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)

        mToolbarTitle = findViewById(R.id.toolbar_title) as TextView
        mToolbarSubTitle = findViewById(R.id.toolbar_subtitle) as TextView

        if (mToolbar != null) {
            //将Toolbar显示到界面
            setSupportActionBar(mToolbar)
        }
        if (mToolbarTitle != null) {
            //getTitle()的值是activity的android:lable属性值
            mToolbarTitle!!.text = title
        }
    }

    override fun onStart() {
        super.onStart()
        /**
         * 判断是否有Toolbar,并默认显示返回按钮
         */
        if (null != getToolbar() && isShowBacking()) {
            showBack()
        }
    }

    /**
     * 获取头部标题的TextView
     * @return
     */
    fun getToolbarTitle(): TextView {
        return mToolbarTitle as TextView
    }

    /**
     * 获取头部副标题的TextView
     * @return
     */
    fun getSubTitle(): TextView {
        return mToolbarSubTitle as TextView
    }

    /**
     * this Activity of tool bar.
     * 获取头部.
     * @return support.v7.widget.Toolbar.
     */
    fun getToolbar(): Toolbar? {
        return findViewById(R.id.toolbar) as Toolbar
    }

    /**
     * 版本号小于21的后退按钮图片
     */
    private fun showBack() {
        //setNavigationIcon必须在setSupportActionBar(toolbar);方法后面加入
        getToolbar()!!.setNavigationIcon(R.mipmap.back)
        getToolbar()!!.setNavigationOnClickListener { onBackPressed() }
    }

    /**
     * 是否显示后退按钮,默认显示,可在子类重写该方法.
     * @return
     */
    open fun isShowBacking(): Boolean {
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.v(TAG, "onDestroy...")
    }
}

